﻿using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;


namespace Zeus.Logger
{
    internal class ZLoggerMessageHandler : DelegatingHandler
    {
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (request.Method.Equals(HttpMethod.Options))
            {
                return await base.SendAsync(request, cancellationToken);
            }

            var dependencyResolver = request.GetConfiguration().DependencyResolver;
            var zloggerObject = dependencyResolver.GetService(typeof(IZLogger));
            var zloggerContextObject = dependencyResolver.GetService(typeof(IZLoggerContext));

            Contract.Assert(zloggerObject != null, "ZLOGGER IS NULL");
            Contract.Assert(zloggerContextObject != null, "ZLOGGERCONTEXT IS NULL");

            var zlogger = zloggerObject as IZLogger;
            var zloggerContext = zloggerContextObject as IZLoggerContext;

            await zloggerContext.BuildContext(request);
            await zlogger.OnRequest(zloggerContext);
            return await base.SendAsync(request, cancellationToken).ContinueWith(responseTask =>
          {
              var response = responseTask.Result;
              zloggerContext.BuildContext(response).Wait();
              zlogger.OnResponse(zloggerContext);
              return response;
          });
        }
    }
}
